## translator.py
import requests
import logging
from typing import Optional
from time import sleep

class Translator:
    """Handles translation via Google Translate API."""

    def __init__(self, api_key: str = "YOUR_API_KEY_HERE"):
        """
        Initializes the Translator with the required Google Translate API key.

        Args:
            api_key (str): Google Translate API key. Default is a placeholder.
        """
        self.api_key = api_key
        self.translate_url = "https://translation.googleapis.com/language/translate/v2"

    def translate(self, text: str, target_language: str = 'zh') -> Optional[str]:
        """
        Translates the given text to the specified target language using Google Translate API.
        This version includes a retry mechanism with a maximum number of attempts.
        """
        params = {'q': text, 'target': target_language, 'key': self.api_key}
        max_retries = 5
        retry_count = 0

        while retry_count < max_retries:
            try:
                response = requests.get(self.translate_url, params=params)
                response.raise_for_status()
                data = response.json()
                return data['data']['translations'][0]['translatedText']
            except requests.exceptions.RequestException as e:
                if e.response and e.response.status_code == 429:
                    logging.error("Google Translate API rate limit exceeded. Retrying...")
                    retry_count += 1
                    sleep(60)  # Wait for 60 seconds before retrying
                else:
                    logging.error(f"Error during translation: {e}")
                    return None
            except KeyError as e:
                logging.error(f"Unexpected response structure: {e}")
                return None
            except Exception as e:
                logging.error(f"Unexpected error: {e}")
                return None
        logging.error("Max retries reached. Translation failed.")
        return None

# Setup basic logging configuration
logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
